package com.jinxin.platform.cdysylives.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdysylives.bean.CdysylivesDeviceTask;
import com.jinxin.platform.cdysylives.bean.CdysylivesMonitorDevice;
import com.jinxin.platform.cdysylives.bean.CdysylivesSecretkey;
import com.jinxin.platform.cdysylives.bean.bo.*;
import com.jinxin.platform.cdysylives.common.CommonCodeEntity;
import com.jinxin.platform.cdysylives.common.Constant;
import com.jinxin.platform.cdysylives.common.ResultEntity;
import com.jinxin.platform.cdysylives.mapper.CdysylivesDeviceTaskMapper;
import com.jinxin.platform.cdysylives.mapper.CdysylivesMonitorDeviceMapper;
import com.jinxin.platform.cdysylives.mapper.CdysylivesSecretkeyMapper;
import com.jinxin.platform.cdysylives.service.IEquipmentService;
import com.jinxin.platform.cdysylives.utils.HttpClientPoolUtil;
import com.jinxin.platform.cdysylives.utils.HttpClientResult;
import com.jinxin.platform.cdysylives.utils.IdWorker;
import com.jinxin.platform.cdysylives.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 那个男人
 * @Date 2023/8/1 16:33
 * @Version 1.0
 */
@EnableScheduling
@Configuration
@Component
public class CdysyliveDeviceTask {
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private CdysylivesSecretkeyMapper secretkeyMapper;
    @Autowired
    private CdysylivesDeviceTaskMapper deviceTaskMapper;
    @Autowired
    private CdysylivesMonitorDeviceMapper monitorDeviceMapper;
    @Value("${cdysylives.api-url.create-project}")
    private String createProjectUrl;
    @Value("${cdysylives.api-url.record-file}")
    private String recordFileUrl;
    @Resource
    private IdWorker idWorker;

    /**
     * 每天凌晨1点开始录制视频
     */
    @Scheduled(cron = "0 0 1 * * ?  ")
    public void startRecordVideo(){
        HashMap param1 = new HashMap();
        param1.put("isEnabled", Constant.ENABLED);
        List<CdysylivesSecretkey> secretList = secretkeyMapper.list(param1);
        if(secretList.size() == 0){return;}
        for(CdysylivesSecretkey secretkey : secretList){
            // 以社区为单位创建项目
            String appKey = secretkey.getAppKey();
            String secret = secretkey.getAppSecret();
            ResultEntity tokenEntity = equipmentService.queryToken(appKey,secret);
            if(CommonCodeEntity.FAIL.equals(tokenEntity.getResultCode())){
                continue;
            }
            String token = (String) tokenEntity.getResultContent();
            HashMap param2 = new HashMap();
            param2.put("communityId",secretkey.getCommunityId());
            List<CdysylivesMonitorDevice> deviceList = monitorDeviceMapper.list(param2);
            if(deviceList.size() == 0){continue;}
            String pId = "";
            for(CdysylivesMonitorDevice device : deviceList){
                String projectId = device.getProjectId();
                // 没有创建项目就新建一个
                String deviceId = device.getId();
                String deviceSerial = device.getDeviceSerial();
                if(StringUtils.isEmpty(pId)){
                    try {
                        String prId = Utils.getRandom9()+"";
                        String url = this.createProjectUrl + prId;
                        Map<String, String> params = new HashMap<>();
                        params.put("accessToken", token);
                        params.put("projectName", device.getCommunityName());
                        //项目文件过期天数，0表示不过期，标准存储，不输入默认30天，归档存储，不输入默认60天，范围：0~36500天
                        params.put("expireDays", Constant.STRING_ZERO);
                        //params.put("storageType", "");//项目存储类型，默认标准存储。1-标准存储,2-存档存储
                        //params.put("flowLimit", "");//项目下载流量限制，单位：字节
                        HttpClientResult clientResult = HttpClientPoolUtil.doPost(url, params, true);
                        if(Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                            YsyResult response = JSON.parseObject(clientResult.getContent(), YsyResult.class);
                            MetaInfo meta = response.getMeta();
                            if(!Constant.REQUEST_STATUS_SUCCEED.equals(meta.getCode())){
                                return;
                            }
                            // 创建成功
                            pId = prId;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if(StringUtils.isEmpty(projectId)){
                    //更新设备的项目ID
                    CdysylivesMonitorDevice newDevice = new CdysylivesMonitorDevice();
                    newDevice.setId(deviceId);
                    newDevice.setProjectId(pId);
                    monitorDeviceMapper.updateByKey(newDevice);
                    projectId = pId;
                }
                // 项目有就直接创建录制视频任务
                saveTask(deviceSerial,token,projectId,deviceId);
            }
        }
    }

    private void saveTask(String deviceSerial,String token,String projectId,String deviceId){
        Map<String,String> headers = new HashMap<>();
        headers.put("accessToken",token);
        headers.put("deviceSerial",deviceSerial);
        Map<String,String> params = new HashMap<>();
        params.put("projectId",projectId);
        //params.put("recordSeconds",86400+""); //录制时长,单位秒，默认86400秒（24小时）
        //params.put("validateCode","");//录像解密密钥， 若设备加密则必须填写，否则视频无法录制成功
        //params.put("voiceSwitch","2");//录制视频声音开关, 0.关 1.开 2.自动 默认2
        try {
            HttpClientResult taskResult =
                    HttpClientPoolUtil.doPost(this.recordFileUrl, headers, params, true);
            if(Constant.REQUEST_STATUS_SUCCEED.equals(taskResult.getCode())){
                YsyResult response = JSON.parseObject(taskResult.getContent(), YsyResult.class);
                MetaInfo meta = response.getMeta();
                if(!Constant.REQUEST_STATUS_SUCCEED.equals(meta.getCode())){
                    return;
                }
                JSONObject taskJson = JSONObject.parseObject(response.getData());
                String taskId = taskJson.getString("taskId");
                if(!StringUtils.isEmpty(taskId)){
                    CdysylivesDeviceTask deviceTask = new CdysylivesDeviceTask();
                    deviceTask.setId(idWorker.nextId()+"");
                    deviceTask.setTaskId(taskId);
                    deviceTask.setDeviceId(deviceId);
                    deviceTask.setCreateTime(LocalDateTime.now());
                    deviceTaskMapper.insert(deviceTask);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
